<script lang="ts" setup>
const toast = useToast();

const fakeFilePath = ref<string>();
const fileSrc: Ref<FileList | null> = ref<FileList | null>(null);
const uploadedList = ref<FileMetaType[]>([]);
const showPlayer = ref(false)
const videoSrc = ref('')
const uploadedListSession = useSessionStorage<FileMetaType[]>("uploadedVideoList", []);
onMounted(async () => {
  if (uploadedListSession.value.length > 0) {
    uploadedList.value = uploadedListSession.value;
    return
  }
  const uploadDataDir = await $fetch("/api/supervision/upload")
  uploadedListSession.value = uploadDataDir.data.map((d: string) => {
    return {
      name: d.split('\\')[1],
      type: `video/${d.split('.')[1]}`,
      canPlay: true,
    }
  })
  uploadedList.value = uploadedListSession.value;
})
const doShow = (videoName: string) => {
  if (!showPlayer.value) 
    showPlayer.value = true
  
  videoSrc.value = `/upload/video/${videoName}`
}

function handleFile(file: FileList): void {
  if (file.length > 0 && uploadedList.value.length > 0) {
    const res = uploadedList.value.find((f) => {
      return f.name === file[0].name
        // && f.size === file[0].size
        && f.type === file[0].type
    });
    if (res) {
      toast.add({
        title: "文件已存在",
        id: "4782",
        color: "yellow",
        timeout: 3000,
        icon: "i-heroicons-exclamation-circle",
      });
      return
    }
  }
  fileSrc.value = file
  // console.log("file", fileSrc.value?.[0].name, fileSrc.value?.[0].type);
}
async function doUpload() {
  if (!fileSrc.value || fileSrc.value.length === 0) {
    return;
  }
  else if (fileSrc.value[0].size > 1024 * 1024 * 10) {
    toast.add({
      title: "文件过大",
      id: "4782",
      color: "yellow",
      timeout: 3000,
      icon: "i-heroicons-exclamation-circle",
    });
    return;
  }
  const file = fileSrc.value?.[0];
  const formData = new FormData();
  formData.append("file", file);

  const fileMeta: FileMetaType = {
    name: file.name,
    size: file.size,
    type: file.type,
    canPlay: file.type.startsWith("video"),
  };
  const res = await $fetch("/api/supervision/upload", {
    method: "POST",
    body: formData,
    headers: {
      fileMeta: JSON.stringify(fileMeta),
    },
  });
  if (res.msg === "ok") {
    toast.add({
      title: "上传成功",
      id: "5467",
      timeout: 1500,
    });
    dropFile();
    uploadedList.value.push(fileMeta);
  }
}
function dropFile() {
  fakeFilePath.value = undefined;
  fileSrc.value = null;
}
const noFile = computed(() => !fileSrc.value || fileSrc.value.length === 0);
definePageMeta({
  layout: "empty",
});
</script>

<template>
  <UContainer>
    <UCard
      class="rounded-[6px] border-[2px] border-solid p-4 shadow-md m-4"
      :class="noFile ? 'hover:border-red-500' : 'hover:border-green-500'"
    >
      <p class="px-4 font-semibold pb-4">
        文件上传
      </p>
      <div class="w-[400px] h-full">
        <div class="px-6 py-2">
          <UInput
            v-model="fakeFilePath"
            type="file"
            size="sm"
            accept="image/*,video/*"
            :ui="{
              wrapper: tw`relative`,
              // file: tw`file:text-blue-400`.join(' '),
            }"
            @change="(file: FileList) => handleFile(file)"
          />
          <p v-if="!noFile && fileSrc /* 右侧仅用于类型提示 */" class="p-2">
            文件大小 <span class="text-teal-500">{{ fileSrc[0] ? (fileSrc[0].size / 1024).toFixed(2) : 0 }}kb</span>
          </p>
        </div>
        <div class="flex justify-evenly">
          <UButton
            class="w-1/5 justify-center"
            :disabled="noFile"
            @click="doUpload"
          >
            上传
          </UButton>
          <UButton
            class="w-1/5 justify-center"
            :disabled="noFile"
            color="lime"
            @click="dropFile"
          >
            取消
          </UButton>
        </div>
      </div>
    </UCard>
    <!-- <UButton
      @click="
        uploadedList.push({
          type: 'type',
          name: 'name',
          size: 1,
          canPlay: false,
        })
      "
    >
      add
    </UButton> -->
    <UCard
      class="m-4 max-h-[400px] shadow-md" :ui="{
        body:
          {
            padding: tw`!px-2 !py-2 sm:p-6`,
          },
      }"
    >
      <UTable
        class="overflow-y-scroll max-h-[300px]"
        :rows="uploadedList"
        :columns="[
          { key: 'name', label: '文件名' },
          { key: 'type', label: '类型' },
          // { key: 'size', label: '文件大小' },// 不显示文件大小,因为获取时难做
          { key: 'canPlay', label: '测试视频资源' },
        ]"
        :ui="{
          thead: tw`sticky top-0 bg-white z-10`,
        }"
      >
        <template
          #name-header="{ column }: { column: { key: string; label: string } }"
        >
          <p class="w-[120px] relative left-2">
            {{ column.label }}
          </p>
        </template>

        <template
          #type-header="{ column }: { column: { key: string; label: string } }"
        >
          <p class="flex justify-center">
            {{ column.label }}
          </p>
        </template>
        <template #type-data="{ row }: { row: FileMetaType }">
          <p class="flex justify-center">
            {{ row.type }}
          </p>
        </template>

        <template
          #size-header="{ column }: { column: { key: string; label: string } }"
        >
          <p class="flex justify-center">
            {{ column.label }}
          </p>
        </template>
        <!-- <template #size-data="{ row }: { row: FileMetaType }">
          <p class="flex justify-center">
            {{ (row.size / 1024).toFixed(2) }}kb
          </p>
        </template> -->
        <template #canPlay-data="{ row }: { row: FileMetaType }">
          <p class="flex justify-center">
            <UButton v-if="row.canPlay" @click="() => doShow(row.name)">
              测试
            </UButton>
          </p>
        </template>
      </UTable>
      <div v-if="showPlayer">
        <ClientOnly>
          <ThePlayer :src="videoSrc" />
          <template #fallback>
            <FallBack />
          </template>
        </ClientOnly>
      </div>
    </UCard>
  </UContainer>
</template>

<style scoped>
</style>
